#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    //分配空间，指定父对象
    udpSocket = new QUdpSocket(this);
    //绑定端口
    udpSocket->bind(8888);

    /**
     * @brief 组播-类似创建QQ群
    //修改绑定端口
    udpSocket->bind(QHostAddress::AnyIPv4,8888);
    //加入某组播，组播是D类地址
    udpSocket->joinMulticastGroup(QHostAddress("224.0.0.2"));
   // udpSocket->leaveMulticastGroup(QHostAddress("224.0.0.2"));//退出组播
     */

    setWindowTitle("端口：8888");

    //对方发送数据过来时会自动触发readyRead()
    connect(udpSocket,&QUdpSocket::readyRead,this,&Widget::dealMsg);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::dealMsg()
{
    //读取对方发送的内容
    char buf[1024] = {0};
    QHostAddress Addr;
    quint16 port;
   qint64 len = udpSocket->readDatagram(buf,sizeof (buf),&Addr,&port);
   if(len > 0)
   {
       QString str = QString("[%1:%2] %3").arg(Addr.toString()).arg(port).arg(buf);
       ui->textEdit->setText(str);
   }
}

void Widget::on_buttonSend_clicked()
{
    //先获取对方IP和端口
    QString ip = ui->lineEditIP->text();
    quint16 port = ui->lineEditPort->text().toUShort();

    QString str = ui->textEdit->toPlainText();

    udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port);
}
